import utils from "../../../utils/utils";
import {
  formatTimeDate
} from "../../../utils/formatData";
import {
  taskhallHttp
} from '../../../api/task.js';
const taskHttp = new taskhallHttp();
import Data from "../../../utils/data";
import User from "../../../utils/user";
Page({

  /**
   * 页面的初始数据
   */
  pushOld: false,
  videoAd: null,
  data: {
    id: 0, //传入页面id
    redpackageTaskInfo: {}, //页面信息
    thisType: 0, //当前选中的按钮
    isShowPreViewImage: false,
    previewHeight: '',
    previewImage: '',
    isRetractMove: false, //是否显示收起按钮
    ekey: '',
    showRedtaskrecords: 3,
    s_ekey: '',
    dict: {},
    userInfo: {},
    btnType: 2, //0 已完成 1领取任务金  2做任务
    btnStyle: [{
        btnText: '任务已完成',
        btnDes: '(您的任务已经完成)',
        btnClick: '',
        btnCss: 'color-ok'
      }, {
        btnText: '领取任务奖金',
        btnDes: '(领取任务奖金)',
        btnClick: 'httpReceiveRedpackage',
      }, {
        btnText: '',
        btnDes: '',
        btnClick: '',
      },

    ],
    isShowRedPopup: false,
    redPopupBg: utils.pageUrl + "mini/images/redpacket/redpacket_open_bg.png",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  initPage: function(options) {
    this.dayLookAdNum()
    let self = this
    if (options.hasOwnProperty('id')) {
      this.setData({
        id: options.id
      })
    }
    setTimeout(function() {
      self.createVideoAd(); //初始化广告
    }, 1000);
    this.initData();
    if (options.hasOwnProperty('ekey')) {
      utils.UserUv(options.ekey);
      User.UvTrackPut(options.ekey);
    }
  },
  initData() {
    let self = this;
    Data.getDictConfig('task_config', function(res) {
      self.setData({
        dict: res
      })
    }, true);
    wx.showNavigationBarLoading();
    self.httpTaskMainInfo();
    self.initPreviewHeight();
    self.getUserInfo(function(userInfo) {
      self.setData({
        userInfo: userInfo
      });
    }, false);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.initData()
  },
  changPreview() {
    let self = this;
    this.httpPicMaterialV4(self.data.redpackageTaskInfo.redpackage_details.material_id, function() {
      self.setData({
        isShowPreViewImage: !self.data.isShowPreViewImage,
      });
    });
  },
  goToMain() {
    wx.switchTab({
      url: '/pages/task/main/main',
    })
  },
  //获取红红包详情页面信息
  httpTaskMainInfo() {
    let self = this
    taskHttp.redpackageTaskDetails({
      red_id: this.data.id
    }).then(res => {
      //随机切换任务类型
      // let randType = 1;
      // let type = [];
      res = this.formatData(res);
      // for (let i = 0; i < res.redpackage_details.task_type.length; i++) {
      //   if(!res.isAdvert && res.redpackage_details.task_type[i]['red_task_type'] === 3){
      //     continue;
      //   }
      //   type.push(res.redpackage_details.task_type[i]['red_task_type']);
      // }
      // if (type.length > 0) {
      //   randType = type[utils.getRandom(type.length - 1, 0)];
      // }
      this.isShowType(res)
      self.setData({
        redpackageTaskInfo: res,
        // thisType: randType
      });
      wx.stopPullDownRefresh()
      wx.hideNavigationBarLoading()
    })
  },
  isShowType(res) {
    let type = -1;
    let style = this.data.btnStyle
    let btnStype = {}
    console.log(wx.getStorageSync('taskType', 1))
    let dayNum = parseInt(wx.getStorageSync('adNum', 0))
    if (wx.getStorageSync('taskType', 1) === 1 && dayNum < 3) {
      wx.setStorageSync('taskType', 2)
      type = 2
      btnStype['btnText'] = '点击做红包任务'
      btnStype['btnDes'] = '(红包任务：看完视频广告任务加' + res.adFen + '分)'
      btnStype['btnClick'] = 'onViewAd'
      btnStype['type'] = 'lookad'
    } else {
      wx.setStorageSync('taskType', 1)
      type = 2
      btnStype['btnText'] = '点击做红包任务'
      btnStype['btnDes'] = '(红包任务：分享好友任务加' + res.newPeopleFen + '分)'
      btnStype['btnClick'] = 'changPreview'
      btnStype['type'] = 'share'
    }
    //如果没有记录则锁定看视频
    if (res.redtaskrecords.length <= 0) {
      type = 2
      btnStype['btnText'] = '点击做红包任务'
      btnStype['btnDes'] = '(红包任务：看完视频广告任务加' + res.adFen + '分)'
      btnStype['btnClick'] = 'onViewAd'
      btnStype['type'] = 'lookad'
    }
    //如果已完成分数大于等于任务分数则显示完成
    if (res.redpackage_details.task_fraction <= res.fraction) {
      type = 1
    }
    //如果已领取则显示任务完成
    if (res.isReceive === 1) {
      type = 0
    }
    if (type === 2) {
      style[type] = btnStype
    }
    console.log('type', type)
    console.log('style', style)
    console.log(btnStype)
    this.setData({
      btnType: type,
      btnStyle: style
    })
  },
  formatData(res) {
    let newPeople = 0 //拉新数
    let oldPeople = 0 //拉老用户数
    let adNum = 0 //看广告次数
    let newPeopleFen = 0 //拉新用户分数
    let oldPeopleFen = 0 //拉老用户分数
    let adFen = 0 //广告分数
    let percentage = 0 //进度条百分比
    let userList = [] //用户列表
    if (res.redtaskrecords.length > 0) {
      let i = 0;
      for (i; i < res.redtaskrecords.length; i++) {
        if (res.redtaskrecords[i].red_task_type === 1) {
          newPeople = newPeople + 1
        }
        if (res.redtaskrecords[i].red_task_type === 2) {
          oldPeople = oldPeople + 1
        }
        if (res.redtaskrecords[i].red_task_type === 3) {
          adNum = adNum + 1
        }
        if (res.redtaskrecords[i].red_task_type !== 3) {
          userList.push(res.redtaskrecords[i])
        }
      }
    }
    let y = 0
    for (y; y < res.redpackage_details.task_type.length; y++) {
      if (res.redpackage_details.task_type[y].red_task_type == 1) {
        newPeopleFen = res.redpackage_details.task_type[y].branch
      }
      if (res.redpackage_details.task_type[y].red_task_type == 2) {
        oldPeopleFen = res.redpackage_details.task_type[y].branch
      }
      if (res.redpackage_details.task_type[y].red_task_type == 3) {
        adFen = res.redpackage_details.task_type[y].branch
      }

    }
    if (res.fraction === 0) {
      percentage = 0
    } else if (res.fraction > res.redpackage_details.task_fraction) {
      percentage = 100
    } else {
      percentage = (res.fraction / res.redpackage_details.task_fraction) * 100
    }
    console.log(percentage)
    res['percentage'] = percentage
    res['newPeopleFen'] = newPeopleFen
    res['oldPeopleFen'] = oldPeopleFen
    res['adFen'] = adFen
    res['newPeople'] = newPeople
    res['oldPeople'] = oldPeople
    res['adNum'] = adNum
    res['userList'] = userList;
    res['isAdvert'] = res.hasOwnProperty('isAdvert') ? res.isAdvert : true;
    console.log(res)
    return res
  },
  httpPicMaterialV4(materialId, callback) {
    let self = this;
    self.getUserInfo(function(userInfo) {
      if (!self.data.previewImage) {
        utils.loading('素材生成中...');
        taskHttp.getPicMaterialV4({
          material_id: materialId,
          inviter_id: userInfo.uid,
          red_task_id: parseInt(self.data.id),
        }).then(res => {
          console.log(res);
          utils.closeLoading();
          self.setData({
            previewImage: res.url,
            ekey: res.ekey
          });
          callback && callback()
        }).catch((res) => {
          utils.closeLoading();
        })
      } else {
        callback && callback();
      }
    })

  },
  // //点击任务前面按钮
  // clickRedIcon(e) {
  //   let type = utils.fixInt(e.currentTarget.dataset.type);
  //   if(type === 3){
  //     if(this.data.redpackageTaskInfo.hasOwnProperty('isAdvert') && !this.data.redpackageTaskInfo.isAdvert) {
  //       utils.msg('观看广告任务达到上限！');
  //       return false;
  //     }
  //   }
  //   this.setData({
  //     thisType: type
  //   })
  // },
  createVideoAd(type) {
    let self = this
    type = type || 1;
    // 在页面onLoad回调事件中创建激励视频广告实例
    console.log('createVideoAd:', self.videoAd, type);
    if (wx.createRewardedVideoAd && !self.videoAd) {
      let adId = utils.getAdId();
      self.videoAd = wx.createRewardedVideoAd({
        adUnitId: adId,
      });
      self.videoAd.onLoad((res) => {
        console.log('激励视屏加载成功', res);
      });
      self.videoAd.onError((err) => {
        console.log(err);
      });
      self.videoAd.onClose((status) => {
        console.log('关闭广告：', status);
        if (status && status.isEnded || status === undefined) {
          // 看广告 - 看完关闭
          return taskHttp.createRedPackageAdvert({
            red_id: self.data.id,
            ad_id: adId
          }).then(res => {
            self.dayLookAdNum()
            self.initData()
          })
        } else {
          // 看广告 - 中途关闭
          utils.msg(`未观看完广告`)
        }
        //销毁当前广告位，重新创建
      });
    }
    if (type === 2) {
      self.videoAd.load();
      self.videoAd.show().then((res) => {
        console.log('广告显示2：', res);
      }).catch((err) => {
        console.log('广告显示失败2：', err);
      });
    }
  },
  //设置每天看广告次数
  dayLookAdNum() {
    //判断当天日期
    var timestamp = new Date();
    let time = formatTimeDate(timestamp, 'yyyyMMdd') //今天日期
    let day = wx.getStorageSync('day', time) //缓存日期 没有则默认今天日期
    if (day === time) { //如果今天等于缓存
      let dayNum = parseInt(wx.getStorageSync('adNum', 0))
      if (dayNum < 3) {
        wx.setStorageSync('adNum', dayNum + 1)
      }
    } else {
      wx.setStorageSync('day', time)
      wx.setStorageSync('adNum', 1)
    }
    console.log(day+'日看广告'+wx.getStorageSync('adNum'))
  },

  onViewAd() {
    this.videoAd.load().then((res) => {
      console.log('广告显示3：', res);
      this.videoAd.show().then((res) => {
        console.log('广告显示2：', res);
      }).catch((err) => {
        console.log('广告显示失败2：', err);
      });
    }).catch(err => {
      console.log('广告显示失败2：', err);
      utils.msg('加载失败，请稍后重试')
    });
  },

  onUnload() {
    console.log('退出页面');
    this.videoAd = null;
  },

  changShowRedPopup() {
    this.setData({
      isShowRedPopup: !this.data.isShowRedPopup
    })
  },

  httpReceiveRedpackage() {
    taskHttp.receiveRedpackage({
      red_id: this.data.id
    }).then(res => {
      this.initData()
      this.changShowRedPopup()
    })
  },

  initPreviewHeight() {
    let self = this
    let systemInfo = wx.getSystemInfoSync();
    let height = systemInfo.windowHeight;
    let rpxHeight = utils.rpxToPx(220);
    let padding = utils.rpxToPx(120);
    self.setData({
      previewBoxHeight: 'height:' + (height - (rpxHeight + padding)) + 'px;',
      previewHeight: 'height:' + (height - (rpxHeight + padding)) + 'px;',
    });
  },
  showMove() {
    this.setData({
      isRetractMove: true,
      showRedtaskrecords: this.data.redpackageTaskInfo.redtaskrecords.length
    })
  },
  retractMove() {
    this.setData({
      isRetractMove: false,
      showRedtaskrecords: 3
    })
  },
  saveImage: function() {
    let self = this;
    let callback;
    if (self.data.previewImage === '') {
      utils.msg('请先获取分享图片');
      return false;
    }
    callback = function() {
      wx.getImageInfo({
        src: self.data.previewImage,
        success(res) {
          console.log(res);
          wx.saveImageToPhotosAlbum({
            filePath: res.path,
            success(res) {
              utils.msg('分享图片保存成功！');
            },
            fail(res) {
              utils.msg('分享图片保存失败，请稍候再试！');
            }
          });
        },
        fail(res) {
          utils.msg('分享图片拉取失败，请稍候再试！');
        }
      });
    };
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              callback();
            },
            fail() {
              utils.msg('您拒绝了保存权限，无法下载到相册');
            }
          })
        } else {
          callback();
        }
      },
      fail(res) {
        utils.msg('获取权限设置失败，请稍候再试！');
      }
    });
  },
  onShareAppMessage() {
    let tm = '?tm=' + utils.getRandom(999, 100);
    let {
      redpackageTaskInfo,
      ekey
    } = this.data;
    let shareTitle, imageUrl, sharePath;
    try {
      shareTitle = redpackageTaskInfo.redpackage_details.red_share_title;
      imageUrl = redpackageTaskInfo.redpackage_details.push_img;
      sharePath = redpackageTaskInfo.redpackage_details.share_path;
    } catch (e) {}
    if (!sharePath) {
      sharePath = '/pages/task/main/main';
    }
    let data = {
      title: shareTitle,
      imageUrl: imageUrl + tm,
      path: sharePath + '?ekey=' + ekey,
    };
    console.log('ShareConfig', data);
    return data;
  },
});
